package com.naicha.wechat.wechat.face;

import java.io.*;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

/**
 * @author NaiCha
 * @date 2019/5/10 8:17
 * @description 面试编程题
 **/
public class face {

    /**
     * 文件拷贝 基于BIO实现 java7 TWR无需释放资源
     * @param source
     * @param target
     */
    public static void fileCope(String source,String target) throws IOException{
        try (FileInputStream inputStream = new FileInputStream(source)){
            try (FileOutputStream outputStream = new FileOutputStream(target)){
                byte[] bytes = new byte[2048];
                int byteToRead;
                while ((byteToRead = inputStream.read(bytes)) != -1){
                    outputStream.write(bytes,0,byteToRead);
                }
            }
        }
    }

    /**
     * 文件拷贝 基于NIO实现 java7 TWR无需释放资源
     * @param source
     * @param target
     */
    public static void fileCopyNIO(String source,String target) throws IOException{
        try (FileInputStream inputStream = new FileInputStream(source)){
            try (FileOutputStream outputStream = new FileOutputStream(target)){
                FileChannel inputChannel = inputStream.getChannel();
                FileChannel outputChannel = outputStream.getChannel();
                ByteBuffer buffer = ByteBuffer.allocate(2048);
                while (inputChannel.read(buffer) != -1){
                    buffer.flip();
                    outputChannel.write(buffer);
                    buffer.clear();
                }
            }
        }
    }

    /**
     * 统计一个单词在一个文件中出现的次数
     * @param source
     * @param word
     */
    public int countWordINFile(String source,String word) throws IOException{
        int count = 0;
        try (FileReader reader = new FileReader(source);BufferedReader bufferedReader = new BufferedReader(reader)){
            String  line = null;
            while ((line = bufferedReader.readLine()) != null){
                int index = -1;
                while (line.length() >= word.length() && (index = line.indexOf(word)) > 0){
                    count++;
                    //打印下标
                    System.out.println(index);
                }
            }
        }
        return count;
    }

    /**
     * 冒泡排序(简版)
     */
    public static void mpSort(){
        int[] numberArr = new int[]{3,2,5,4,9,7,1};
        for (int i=0;i<numberArr.length;i++){
            for (int j=i+1;j<numberArr.length;j++){
                if (numberArr[i] > numberArr[j]){
                    int temp = numberArr[i];
                    numberArr[i] = numberArr[j];
                    numberArr[j] = temp;
                }
            }
        }
        for (int i:numberArr){
            System.out.println(i);
        }
    }



    public static void main(String[] args) {
        mpSort();
    }


}
